<template>
  <el-drawer
    v-model="visible"
    title="链路流程图"
    size="80%"
    destroy-on-close
  >
    <div class="mermaid-container">
      <div v-loading="loading" class="mermaid-wrapper">
        <div v-if="error" class="error-message">
          {{ error }}
        </div>
        <div v-else ref="mermaidRef" class="mermaid">
          {{ mermaidContent }}
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { API_URL } from '@/utils/config'

const props = defineProps({
  modelValue: Boolean,
  linkId: {
    type: [Number, String],
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'nodeClick'])

const visible = ref(props.modelValue)
const mermaidContent = ref('')
const mermaidRef = ref(null)
const loading = ref(false)
const error = ref('')

// 监听visible变化，同步父组件的v-model
watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 监听父组件传入的v-model值
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val && props.linkId) {
    fetchLinkFlow()
  }
})

// 修改点击事件处理函数
const handleNodeClick = (nodeId) => {
  emit('nodeClick', nodeId)
}

// 获取链路流程图数据
const fetchLinkFlow = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const response = await fetch(`${API_URL}/logs/link/${props.linkId}`)
    const data = await response.json()
    
    if (data.code === 0 && data.data?.mermaid_content) {
      mermaidContent.value = data.data.mermaid_content
      await nextTick()
      await renderMermaid()
    } else {
      error.value = '获取流程图数据失败'
    }
  } catch (error) {
    console.error('获取链路流程图失败:', error)
    error.value = '获取链路流程图失败'
    ElMessage.error('获取链路流程图失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.mermaid-container {
  padding: 10px;
  height: 100%;
  overflow: auto;
}

.mermaid-wrapper {
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  min-height: 200px;
}

.mermaid {
  width: 100%;
  height: 100%;
}

.error-message {
  color: #f56c6c;
  text-align: center;
  padding: 20px;
}

:deep(.node rect) {
  padding: 40px !important;
}

:deep(.node .label) {
  padding: 40px !important;
}

:deep(.node) rect {
  rx: 5px;  /* 圆角 */
  ry: 5px;
}

:deep(.node .label foreignObject) {
  padding: 2px !important;
  line-height: 1.2 !important;
}

:deep(.node .label div) {
  padding: 2px 4px !important;
}

:deep(.edgeLabel foreignObject) {
  padding: 2px !important;
}

/* 添加节点悬停效果 */
:deep(.node:hover) {
  opacity: 0.8;
}
</style> 